/**
 * Created at 15/11/25.
 * @Author Ling.
 * @Email i@zeroling.com
 */
"use strict";
const request = require('request'),
    iconv = require('iconv-lite'),
    fs = require('fs');

const loginUri = 'http://uzone.univs.cn/sso.action',
    checkCodeUri = 'http://mzml.univs.cn:8081/common/checkcode',
    ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.10 Safari/537.36';

function getMzmlJSID() {
    return new Promise((resolve, reject) => {
        request.get({
            url: 'http://mzml.univs.cn:8081/common/issigin',
            encoding: null
        }, (error, response, body) => {
            if (error) {
                return reject(error);
            }
            resolve(response.headers['set-cookie'][0].match(/JSESSIONID=([^\s]+)/)[0]);
        });
    });
}

function login(account) {
    return new Promise((resolve, reject) => {
        request.post({
            url: loginUri,
            form: {
                'gUser.loginName': account.email,
                'gUser.password': account.pwd
            },
            headers: {
                'User-Agent': ua,
                'Origin': 'http://mzml.univs.cn:8081',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': 'http://uzone.univs.cn/sso.action'

            },
            encoding: null
        }, (error, response, body) => {
            if (error) {
                //console.log(error);
                return reject(error);
            }
            let cookie = response.headers['set-cookie'].map(c => c.match(/^([^;]*)/)[0]).join('; ');
            var uzoneJSESSIONID = cookie.match(/JSESSIONID=([^\s]+)/, '')[0];
            cookie = cookie.replace(/JSESSIONID=([^\s]+)/, '');
            resolve({
                cookie: cookie,
                uzoneJSESSIONID: uzoneJSESSIONID
            });
        });
    });
}

function checkCode(cookie, mzmlJSESSIONID) {
    return new Promise((resolve, reject) => {
        request.get({
            url: checkCodeUri,
            headers: {
                'User-Agent': ua,
                'Origin': 'http://mzml.univs.cn:8081',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': 'http://mzml.univs.cn:8081/login.html',
                'Cookie': mzmlJSESSIONID + cookie
            },
            encoding: null
        }, (error, response, body) => {
            if (error) {
                //console.log(error);
                return reject(error);
            }
            let checkData = JSON.parse(body.toString());
            resolve(checkData.data);
        });
    });

}

function checkSSO(data, cookie, uzoneJSESSIONID) {
    let uri = `http://uzone.univs.cn/checkSSOLogin.action?token=${data.date}&subSiteId=${data.subSiteId}&checkCode=${data.checkout}&returnUrl=http://mzml.univs.cn:8081/land.html`;
    return new Promise((resolve, reject) => {
        request.get({
            url: uri,
            headers: {
                'User-Agent': ua,
                'Origin': 'http://mzml.univs.cn:8081',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': 'http://mzml.univs.cn:8081/login.html',
                'Cookie': uzoneJSESSIONID + cookie
            },
            encoding: null
        }, (error, response, body) => {
            if (error) {
                //console.log(error);
                return reject(error);
            }
            //console.log(body.toString().match('登陆成功') ? "登陆成功" : "登陆失败");
            data.raw = response.client._httpMessage.path;
            resolve(`${cookie}; token=${data.date}`)
        });
    });

}

function signIn(data, cookie, mzmlJSESSIONID) {
    let uId = data.raw.match(/uId=(\w+)/)[1];
    let token = data.date;
    let checkcode = data.raw.match(/checkCode=(\w+)/)[1];

    return new Promise((resolve, reject) => {
        request.post({
            url: 'http://mzml.univs.cn:8081/user/sigin',
            headers: {
                'User-Agent': ua,
                'Origin': 'http://mzml.univs.cn:8081',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': `http://mzml.univs.cn:8081/land.html?checkCode=${checkcode}&uId=${uId}`,
                'Cookie': mzmlJSESSIONID + cookie
            },
            form: {
                checkcode: checkcode,
                uid: uId,
                token: token
            },
            encoding: null
        }, (error, response, body) => {
            if (error) {
                //console.log(error);
                return reject(error);
            }
            // console.log(body.toString());
            //console.log(`登陆跳转${JSON.parse(body.toString()).status ? "成功" : "失败"}`);
            resolve('ok');
        });
    });
}

function addVote(cookie, mzmlJSESSIONID, form) {
    let uri = 'http://mzml.univs.cn:8081/user/addvote';
    return new Promise((resolve, reject) => {
        request.post({
            url: uri,
            headers: {
                'User-Agent': ua,
                'Origin': 'http://mzml.univs.cn:8081',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': 'http://mzml.univs.cn:8081/webcontent.html?id=130',
                'Cookie': mzmlJSESSIONID + cookie
            },
            form: form,
            encoding: null
        }, (error, response, body) => {
            if (error) {
                // console.log(error);
                return resolve(false);
            }
            try {
                let data = JSON.parse(body.toString());
                if (data && data.status) {
                    return resolve(true);
                } else {
                    return resolve(false);
                }
            } catch (e) {
                return resolve(false);
            }
        });
    });
}

function run(account) {
    let data, cookie, uzoneJSESSIONID, mzmlJSESSIONID;
    return new Promise((resolve, reject) => {
        getMzmlJSID()
        .then(_mzmlJSESSIONID => {
            mzmlJSESSIONID = _mzmlJSESSIONID;
            return login(account);
        })
        .then(_loginRet => {
            cookie = _loginRet.cookie;
            uzoneJSESSIONID = _loginRet.uzoneJSESSIONID;
            return checkCode(cookie, uzoneJSESSIONID)
        })
        .then(_data => {
            data = _data;
            return checkSSO(data, cookie, uzoneJSESSIONID);
        })
        .then(newCookie => {
            cookie = newCookie;
            return signIn(data, cookie, mzmlJSESSIONID);
        })
        .then(empty => Promise.all([
                addVote(cookie, mzmlJSESSIONID, {type: 1, id: 130}),
                addVote(cookie, mzmlJSESSIONID, {type: 2, id: 80}),
            ]))
        .then(rets => {
            if (rets[0]) {console.log(`成功! ${account.email} 给红岩网校+1`);}
            if (rets[1]) {console.log(`成功! ${account.email} 给小帮手+1`);}
            resolve(account);
        })
        .catch(e => {
            // console.log(e);
            reject(e);
        });
    });
}

module.exports = run;